<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import * as echarts from 'echarts/core'
import { LineChart, PieChart, BarChart } from 'echarts/charts'
import type { LineSeriesOption, PieSeriesOption, BarSeriesOption } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent,
  ToolboxComponent
} from 'echarts/components'
import type {
  TitleComponentOption,
  TooltipComponentOption,
  GridComponentOption,
  LegendComponentOption,
  DataZoomComponentOption,
  ToolboxComponentOption
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import type { EChartsType } from 'echarts/core'
import { ArrowUp, ArrowDown, Download, Refresh, DataAnalysis, Monitor } from '@element-plus/icons-vue'

// 注册必要的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent,
  ToolboxComponent,
  LineChart,
  PieChart,
  BarChart,
  CanvasRenderer
])

// 定义图表选项类型
type ECOption = echarts.ComposeOption<
  | LineSeriesOption
  | PieSeriesOption
  | BarSeriesOption
  | TitleComponentOption
  | TooltipComponentOption
  | GridComponentOption
  | LegendComponentOption
  | DataZoomComponentOption
  | ToolboxComponentOption
>

const props = defineProps({
  keyword: {
    type: String,
    required: true
  },
  category: {
    type: String,
    default: ''
  },
  startDate: {
    type: String,
    default: () => {
      const date = new Date()
      date.setDate(date.getDate() - 7)
      return date.toISOString().split('T')[0]
    }
  },
  endDate: {
    type: String,
    default: () => new Date().toISOString().split('T')[0]
  }
})

// 图表引用
const trendChartRef = ref<HTMLElement | null>(null)
const sentimentChartRef = ref<HTMLElement | null>(null)
const sourceChartRef = ref<HTMLElement | null>(null)

// 图表实例
const trendChart = ref<EChartsType | null>(null)
const sentimentChart = ref<EChartsType | null>(null)
const sourceChart = ref<EChartsType | null>(null)

// 加载状态
const loading = ref(false)

// 日期范围
const dateRange = ref([props.startDate, props.endDate])

// 时间单位
const timeUnit = ref('day')

// 内容过滤
const contentFilter = ref('all')

// 数据统计
const statistics = ref({
  totalMentions: 0,
  positiveMentions: 0,
  negativeMentions: 0,
  neutralMentions: 0,
  avgSentiment: 0,
  topSources: [] as { source: string; count: number }[]
})

// 相关内容
const relatedContents = ref([
  {
    content: '人工智能技术正在迅速发展，为各行业带来了革命性的变化。',
    source: '微博',
    time: '2023-11-10 14:30:25',
    sentiment: 0.75
  },
  {
    content: '有关专家指出，人工智能可能会取代部分工作岗位，需要警惕。',
    source: '知乎',
    time: '2023-11-10 12:15:10',
    sentiment: -0.45
  },
  {
    content: '最新研究表明，人工智能在医疗诊断方面的准确率已接近专业医生。',
    source: '今日头条',
    time: '2023-11-09 18:22:37',
    sentiment: 0.62
  },
  {
    content: '人工智能的伦理问题引发了广泛讨论，各方观点不一。',
    source: '微信',
    time: '2023-11-09 09:45:18',
    sentiment: 0.05
  },
  {
    content: '某公司发布的AI助手被发现存在数据泄露风险，引发用户担忧。',
    source: '抖音',
    time: '2023-11-08 16:33:42',
    sentiment: -0.68
  }
])

// 刷新数据
const refreshData = () => {
  // 重置数据
  statistics.value = {
    totalMentions: 0,
    positiveMentions: 0,
    negativeMentions: 0,
    neutralMentions: 0,
    avgSentiment: 0,
    topSources: []
  }
  
  // 加载新数据
  generateMockData()
}

// 生成模拟数据
const generateMockData = () => {
  loading.value = true
  
  // 模拟异步加载
  setTimeout(() => {
    // 趋势数据
    const now = new Date()
    const days = 7
    const trendData = []
    const sentimentTrendData = []
    
    for (let i = days; i >= 0; i--) {
      const date = new Date()
      date.setDate(now.getDate() - i)
      const dateStr = date.toISOString().split('T')[0]
      
      // 生成随机提及数量
      const mentions = Math.floor(Math.random() * 50) + 10
      const positiveMentions = Math.floor(mentions * (Math.random() * 0.5 + 0.2))
      const negativeMentions = Math.floor(mentions * (Math.random() * 0.4 + 0.1))
      const neutralMentions = mentions - positiveMentions - negativeMentions
      
      trendData.push({
        date: dateStr,
        mentions: mentions
      })
      
      sentimentTrendData.push({
        date: dateStr,
        positive: positiveMentions,
        negative: negativeMentions,
        neutral: neutralMentions
      })
      
      // 累计总数
      statistics.value.totalMentions += mentions
      statistics.value.positiveMentions += positiveMentions
      statistics.value.negativeMentions += negativeMentions
      statistics.value.neutralMentions += neutralMentions
    }
    
    // 计算平均情感值 (范围 -1 到 1)
    statistics.value.avgSentiment = (
      (statistics.value.positiveMentions * 0.7) - 
      (statistics.value.negativeMentions * 0.7)
    ) / statistics.value.totalMentions
    
    // 来源数据
    statistics.value.topSources = [
      { source: '微博', count: Math.floor(Math.random() * 100) + 50 },
      { source: '知乎', count: Math.floor(Math.random() * 80) + 30 },
      { source: '今日头条', count: Math.floor(Math.random() * 60) + 20 },
      { source: '微信', count: Math.floor(Math.random() * 40) + 10 },
      { source: '抖音', count: Math.floor(Math.random() * 30) + 5 }
    ]
    
    // 初始化图表
    initTrendChart(trendData)
    initSentimentChart(sentimentTrendData)
    initSourceChart(statistics.value.topSources)
    
    loading.value = false
  }, 800)
}

// 计算百分比
const getPercentage = (value: number, total: number): number => {
  if (total === 0) return 0
  return Math.round((value / total) * 100)
}

// 获取情感类型
const getSentimentType = (value: number): string => {
  if (value > 0.1) return '正面'
  if (value < -0.1) return '负面'
  return '中性'
}

// 获取情感标签类型
const getSentimentTagType = (value: number): string => {
  if (value > 0.1) return 'success'
  if (value < -0.1) return 'danger'
  return 'info'
}

// 获取情感CSS类名
const getSentimentClass = (value: number): string => {
  if (value > 0.1) return 'positive'
  if (value < -0.1) return 'negative'
  return 'neutral'
}

// 初始化趋势图表
const initTrendChart = (data: any[]) => {
  if (!trendChartRef.value) return
  
  if (trendChart.value) {
    trendChart.value.dispose()
  }
  
  trendChart.value = echarts.init(trendChartRef.value)
  
  const option: ECOption = {
    title: {
      text: '关键词提及趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.date),
      axisLabel: {
        formatter: (value: string) => {
          return value.substring(5) // 只显示月-日
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '提及次数'
    },
    toolbox: {
      feature: {
        saveAsImage: { title: '保存为图片' }
      }
    },
    series: [
      {
        name: '提及次数',
        type: 'line',
        data: data.map(item => item.mentions),
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#409EFF'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64, 158, 255, 0.5)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
          ])
        },
        itemStyle: {
          color: '#409EFF'
        }
      }
    ]
  }
  
  trendChart.value.setOption(option)
  
  window.addEventListener('resize', () => {
    trendChart.value && trendChart.value.resize()
  })
}

// 初始化情感趋势图表
const initSentimentChart = (data: any[]) => {
  if (!sentimentChartRef.value) return
  
  if (sentimentChart.value) {
    sentimentChart.value.dispose()
  }
  
  sentimentChart.value = echarts.init(sentimentChartRef.value)
  
  const option: ECOption = {
    title: {
      text: '情感趋势分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['正面', '中性', '负面'],
      top: '30px'
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.date),
      axisLabel: {
        formatter: (value: string) => {
          return value.substring(5) // 只显示月-日
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '数量'
    },
    series: [
      {
        name: '正面',
        type: 'bar',
        stack: 'sentiment',
        data: data.map(item => item.positive),
        itemStyle: {
          color: '#67C23A'
        }
      },
      {
        name: '中性',
        type: 'bar',
        stack: 'sentiment',
        data: data.map(item => item.neutral),
        itemStyle: {
          color: '#909399'
        }
      },
      {
        name: '负面',
        type: 'bar',
        stack: 'sentiment',
        data: data.map(item => item.negative),
        itemStyle: {
          color: '#F56C6C'
        }
      }
    ]
  }
  
  sentimentChart.value.setOption(option)
  
  window.addEventListener('resize', () => {
    sentimentChart.value && sentimentChart.value.resize()
  })
}

// 初始化来源分析图表
const initSourceChart = (data: { source: string; count: number }[]) => {
  if (!sourceChartRef.value) return
  
  if (sourceChart.value) {
    sourceChart.value.dispose()
  }
  
  sourceChart.value = echarts.init(sourceChartRef.value)
  
  const option: ECOption = {
    title: {
      text: '来源分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 10
    },
    series: [
      {
        name: '来源分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data.map(item => ({
          name: item.source,
          value: item.count
        }))
      }
    ]
  }
  
  sourceChart.value.setOption(option)
  
  window.addEventListener('resize', () => {
    sourceChart.value && sourceChart.value.resize()
  })
}

// 监听属性变化，重新加载数据
watch(
  [() => props.keyword, () => dateRange.value, () => timeUnit.value],
  () => {
    refreshData()
  }
)

// 组件挂载时加载数据
onMounted(() => {
  generateMockData()
})
</script>

<template>
  <div class="keyword-analysis">
    <!-- 加载中遮罩 -->
    <el-loading v-model:full-screen="loading" text="加载中..." />
    
    <!-- 顶部工具栏 -->
    <div class="analysis-toolbar">
      <div class="date-range">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :default-value="[startDate, endDate]"
          style="width: 320px;"
          size="default"
        />
      </div>
      
      <div class="toolbar-actions">
        <el-button-group>
          <el-button type="primary" size="default" :icon="Download">导出数据</el-button>
          <el-button type="primary" size="default" :icon="Refresh" @click="refreshData">刷新数据</el-button>
        </el-button-group>
      </div>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stat-cards">
      <el-card shadow="hover" class="stat-card">
        <div class="stat-content">
          <div class="stat-icon positive">
            <el-icon><DataAnalysis /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-label">总提及量</div>
            <div class="stat-value">{{ statistics.totalMentions }}</div>
            <div class="stat-trend positive">
              <el-icon><ArrowUp /></el-icon> 15% 较昨日
            </div>
          </div>
        </div>
      </el-card>
      
      <el-card shadow="hover" class="stat-card">
        <div class="stat-content">
          <div class="stat-icon" :class="getSentimentClass(statistics.avgSentiment)">
            <el-icon><Monitor /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-label">平均情感值</div>
            <div class="stat-value" :class="getSentimentClass(statistics.avgSentiment)">
              {{ statistics.avgSentiment.toFixed(2) }}
            </div>
            <div class="stat-label">{{ getSentimentType(statistics.avgSentiment) }}</div>
          </div>
        </div>
      </el-card>
      
      <el-card shadow="hover" class="stat-card">
        <div class="stat-content">
          <div class="stat-info full-width">
            <div class="stat-label">情感分布</div>
            <div class="sentiment-distribution">
              <div class="stacked-progress">
                <div 
                  class="stacked-segment positive" 
                  :style="{ width: getPercentage(statistics.positiveMentions, statistics.totalMentions) + '%' }"
                >
                  {{ getPercentage(statistics.positiveMentions, statistics.totalMentions) }}%
                </div>
                <div 
                  class="stacked-segment neutral" 
                  :style="{ width: getPercentage(statistics.neutralMentions, statistics.totalMentions) + '%' }"
                >
                  {{ getPercentage(statistics.neutralMentions, statistics.totalMentions) }}%
                </div>
                <div 
                  class="stacked-segment negative" 
                  :style="{ width: getPercentage(statistics.negativeMentions, statistics.totalMentions) + '%' }"
                >
                  {{ getPercentage(statistics.negativeMentions, statistics.totalMentions) }}%
                </div>
              </div>
              <div class="progress-legend">
                <div class="legend-item positive">正面</div>
                <div class="legend-item neutral">中性</div>
                <div class="legend-item negative">负面</div>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 图表区域 -->
    <div class="chart-section">
      <el-tabs type="border-card">
        <el-tab-pane label="关键词提及趋势">
          <div class="chart-header">
            <h4>关键词提及趋势</h4>
            <el-radio-group v-model="timeUnit" size="small">
              <el-radio-button label="day">按天</el-radio-button>
              <el-radio-button label="week">按周</el-radio-button>
              <el-radio-button label="month">按月</el-radio-button>
            </el-radio-group>
          </div>
          <div ref="trendChartRef" class="chart-container" style="height: 280px;"></div>
        </el-tab-pane>
        
        <el-tab-pane label="情感与来源分析">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="chart-header">
                <h4>情感趋势分析</h4>
              </div>
              <div ref="sentimentChartRef" class="chart-container" style="height: 280px;"></div>
            </el-col>
            
            <el-col :span="12">
              <div class="chart-header">
                <h4>来源分布</h4>
              </div>
              <div ref="sourceChartRef" class="chart-container" style="height: 280px;"></div>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <!-- 相关内容列表 -->
    <el-card shadow="hover" class="content-card" style="margin-top: 15px;">
      <template #header>
        <div class="card-header">
          <span>相关内容</span>
          <el-select v-model="contentFilter" size="small" style="width: 120px;">
            <el-option label="全部" value="all" />
            <el-option label="正面" value="positive" />
            <el-option label="中性" value="neutral" />
            <el-option label="负面" value="negative" />
          </el-select>
        </div>
      </template>
      
      <el-table :data="relatedContents" style="width: 100%" size="small" stripe>
        <el-table-column prop="content" label="内容" min-width="300" show-overflow-tooltip />
        <el-table-column prop="source" label="来源" width="100" />
        <el-table-column prop="time" label="时间" width="150" />
        <el-table-column prop="sentiment" label="情感" width="80">
          <template #default="scope">
            <el-tag 
              :type="getSentimentTagType(scope.row.sentiment)" 
              size="small"
              effect="light"
            >
              {{ getSentimentType(scope.row.sentiment) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          layout="total, prev, pager, next"
          :total="100"
          :page-size="10"
          background
          small
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.keyword-analysis {
  padding: 0;
}

.analysis-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px 0;
}

.toolbar-actions {
  display: flex;
  gap: 10px;
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
  margin-bottom: 15px;
}

.stat-card {
  height: 100%;
  border-radius: 8px;
  transition: transform 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
  font-size: 24px;
  background-color: #f0f2f5;
}

.stat-icon.positive {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67C23A;
}

.stat-icon.neutral {
  background-color: rgba(144, 147, 153, 0.1);
  color: #909399;
}

.stat-icon.negative {
  background-color: rgba(245, 108, 108, 0.1);
  color: #F56C6C;
}

.stat-info {
  flex: 1;
}

.full-width {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 5px;
  line-height: 1.2;
}

.stat-value.positive {
  color: #67C23A;
}

.stat-value.neutral {
  color: #909399;
}

.stat-value.negative {
  color: #F56C6C;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 13px;
}

.stat-trend.positive {
  color: #67C23A;
}

.stat-trend.negative {
  color: #F56C6C;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.sentiment-distribution {
  margin-top: 10px;
}

.stacked-progress {
  height: 20px;
  width: 100%;
  display: flex;
  border-radius: 4px;
  overflow: hidden;
}

.stacked-segment {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
  font-weight: bold;
}

.stacked-segment.positive {
  background-color: #67C23A;
}

.stacked-segment.neutral {
  background-color: #909399;
}

.stacked-segment.negative {
  background-color: #F56C6C;
}

.progress-legend {
  display: flex;
  justify-content: center;
  margin-top: 8px;
  gap: 15px;
}

.legend-item {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.legend-item::before {
  content: '';
  display: inline-block;
  width: 8px;
  height: 8px;
  margin-right: 4px;
  border-radius: 2px;
}

.legend-item.positive::before {
  background-color: #67C23A;
}

.legend-item.neutral::before {
  background-color: #909399;
}

.legend-item.negative::before {
  background-color: #F56C6C;
}

.chart-section {
  margin-bottom: 15px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding: 0 10px;
}

.chart-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.chart-container {
  width: 100%;
}

.content-card {
  margin-bottom: 15px;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

/* 为Tab内容添加样式 */
:deep(.el-tabs__content) {
  padding: 15px;
}

:deep(.el-tabs--border-card) {
  box-shadow: none;
  border: 1px solid #dcdfe6;
}
</style> 